package net.starwifi.duobao.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

public class IpUtils {
    private IpUtils() {
    }

    public static String getIpAddr(HttpServletRequest request) {
        if (request == null) {
            return "unknown";
        }
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        //X-Forwarded-For
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Forwarded-For");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }


    public static String getIpAddress(String ip){
        String county="";
        String  city="";
        try {
            Map<String,Object> p=new HashMap<String, Object>();
            p.put("ip", ip);
            String json=HttpUtils.get("http://ip.taobao.com/service/getIpInfo.php", p);
            JSONObject jsonStr= JSON.parseObject(json);
            if(jsonStr!=null){
                if(jsonStr.getJSONObject("data")!=null){
                    county=jsonStr.getJSONObject("data").getString("country");
                    city=jsonStr.getJSONObject("data").getString("city");
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return county+""+city;
    }
}
